package com.zhouyu.gamecommunity.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;

@Component
public class HttpRequestUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
    private static final String UNKNOWN = "unknown";
    public static final String X_KSP_Token = "7e1b784b92034dceaf198a3b29171cdd";

    /**
     * 获取ip地址
     * 使用Nginx等反向代理软件时，不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X—Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            //以下两个获取在k8s中，将真实的客户端IP，放到了x-Original-Forwarded-For。而将WAF的回源地址放到了x-Forwarded-For了
            ip = request.getHeader("X-Original-Forwarded-For");
            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Forwarded-FOr");
            }
            //获取nginx等代理的ip
            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-forwarded-FOr");
            }

            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }

            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }

            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }

            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            //兼容k8s集群获取ip
            if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if (("0:0:0:0:0:0:0:1").equalsIgnoreCase(ip) || ("127.0.0.1").equalsIgnoreCase(ip)) {
                    //根据ip取本机配置的IP
                    InetAddress iNet = null;
                    try {
                        iNet = InetAddress.getLocalHost();
                        ip = iNet.getHostAddress();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                        logger.error("InetAddress.getLocalHost()发生异常");
                    }
                }
            }

            //使用代理，则获取第一个IP地址
            if (!StringUtils.isEmpty(ip) && ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取厂商ip地址异常");
        }

        return ip;
    }

    /**
     * 测试ip是否联通
     * @param ipAddress
     * @param timeout
     * @return
     */
    public static boolean isIpReachable(String ipAddress, int timeout) {
        try {
            String host = ipAddress;
            int port = 80;
            if (ipAddress.contains(":")){
                host = ipAddress.split(":")[0];
                port = Integer.parseInt(ipAddress.split(":")[1]);
            }
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(host, port), timeout);
            socket.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static InputStream getInputStreamFromUrl(String url, RestTemplate restTemplate) {
        try {
            logger.info("开始请求url输入流--url：" + url);
            HttpHeaders httpHeaders = new HttpHeaders();
            HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
            ResponseEntity<Resource> resultEntity = restTemplate.exchange(
                    url, HttpMethod.GET, httpEntity, Resource.class);
            return resultEntity.getBody().getInputStream();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取案件详情接口通用调用方法
     */
    public static JSONObject invokeAliJsonInterface(String json, String url) {
          JSONObject resultJson = new JSONObject();
        try {
            // HEADER
            HttpHeaders header = new HttpHeaders();
            header.add("Content-Type", "application/json;charset=utf-8");
            // BODY
            HttpEntity<String> requestEntity = new HttpEntity<String>(json, header);
            // POST INTERFACE
            RestTemplate rest = new RestTemplate();
            ResponseEntity<String> resultEntity = rest.postForEntity(url, requestEntity, String.class);
            String resultstr = resultEntity.getBody();
            resultJson = JSONObject.parseObject(resultstr);
            return resultJson;
        } catch (RestClientException e) {
            e.printStackTrace();
            resultJson.put("code",500);
            resultJson.put("msg","请求发生异常");
            return resultJson;
        }
    }

    /**
     * 金额计算请求
     * @param url
     * @return
     */
    public static JSONObject getJejsByIdInterface(String url) {
        JSONObject msg = new JSONObject();
        // HEADER
        HttpHeaders header = new HttpHeaders();
        //BODY
        HttpEntity<String> requestEntity = new HttpEntity<String>(header);
        //POST INTERFACE
        RestTemplate rest = new RestTemplate();
        ResponseEntity<Resource> resultEntity = rest.exchange(url, HttpMethod.GET, requestEntity, Resource.class);
        InputStream ins;
        try {
            ins = Objects.requireNonNull(resultEntity.getBody()).getInputStream();
            msg.put("code", 200);
            msg.put("msg", true);
            msg.put("fileStream", ins);
            msg.put("fileName", URLDecoder.decode(Objects.requireNonNull(resultEntity.getBody().getFilename()), "UTF8"));
        } catch (IOException e) {
            msg.put("code", 500);
            msg.put("msg", false);
            e.printStackTrace();
        }
        return msg;
    }

    public static String voice(String url ,String text){
        if (StrUtil.isBlank(url) || StrUtil.isBlank(text)){
            return null;
        }
        logger.info("获取到入参：{}",text);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(  new MediaType(MediaType.TEXT_PLAIN,StandardCharsets.UTF_8));
        HttpEntity<String> httpEntity = new HttpEntity<>(text, httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(url,
                HttpMethod.POST, httpEntity, String.class);
        String body = exchange.getBody();
        logger.info("获取到转写结果，{}",body);
        return  body;
    }
    public static JSONObject voiceConversion(JSONObject jsonObject1,String httpMethod){
        logger.info("开始请求语音连接服务，参数为:{}",jsonObject1);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-KSP-Token",X_KSP_Token);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("court_name",jsonObject1.getString("court_name"));
        jsonObject.put("court_code",jsonObject1.getString("court_code"));
        jsonObject.put("user_name",jsonObject1.getString("user_name"));
        jsonObject.put("user_id",jsonObject1.getString("user_id"));
        String string = Base64.getEncoder().encodeToString(jsonObject.toJSONString
                ().getBytes(StandardCharsets.UTF_8));
        httpHeaders.add("X-KSP-User",string);
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        if ("post".equals(httpMethod)){
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("appid","szft");
            jsonObject3.put("fileUrl",jsonObject1.getString("fileUrl"));
            jsonObject3.put("bizid",jsonObject1.getString("bizId"));
            jsonObject3.put("lang","chin");
            HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject3, httpHeaders);
            logger.info("开始请求语音连接服务，参数为:{}",jsonObject1);
            if (jsonObject1.getString("fileUrl") == null || jsonObject1.getString
                    ("fileUrl").length() == 0){
                return null;
            }
            String url = "http://192.1.5.30:8080/kspvirtual/lxspyyzx/voice/asr";
            ResponseEntity<String> exchange = restTemplate.exchange(url,
                    HttpMethod.POST, httpEntity, String.class);
            JSONObject jsonObject2 = JSONObject.parseObject(exchange.getBody());
            logger.info("语音连接服务结果:{}",jsonObject2);
            return  jsonObject2;
        }else {
            logger.info("开始请求语音连接服务结果");
            HttpEntity<JSONObject> httpEntity = new HttpEntity<>(null, httpHeaders);
            if (jsonObject1.getString("bizid") == null || jsonObject1.getString

                    ("bizid").length() == 0){
                return null;
            }
            ResponseEntity<String> exchange = restTemplate
                    .exchange("http://192.1.5.30:8080/kspvirtual/lxspyyzx/voice/asr/get?bizid="+jsonObject1.getString("bizid")+"&appid=regfger357458768sdf", HttpMethod.GET, httpEntity, String.class);
            JSONObject jsonObject2 = JSONObject.parseObject(exchange.getBody());
            logger.info("语音连接服务结果:{}",jsonObject2);
            return  jsonObject2;
        }
    }
}
